<?php
/**
 *  學生異動報表
 * @author cik
 *
 */
class StudentTransfer_ReportController extends Zend_Controller_Action
{
    private $_studentParamArr;
    public function init()
    {
        // 報表項目
        $this->view->reportArr = array(8,2,7,11,12,3,14,13) ;
        // 學生資料陣列
        $locale = Bootstrap::$config['resources']['locale']['default'];
        $path = APPLICATION_PATH."/modules/student/languages/$locale/data.ini";
        $ini = new Zend_Config_Ini($path);
        $this->view->arrayData = $ini->get('array_data')->toArray();

        //取系統預設值
        $param = new Default_Model_ModulesParam();
        $this->_studentParamArr = $param->getParamByResourceId('student');
    }

    public function indexAction()
    {
        // action body
    }

    public function setAction()
    {
        $act = (string) $this->_getParam('act');
        if ($act == 'print-report') // 列印異動名冊
        $this->_printReport();
        elseif ($act == 'print-cover') // 列印封面
        $this->_printCover();
        elseif ($act == 'assign-word') // 填入字號
        $this->_assignWord();
        elseif($act == 'print-report-new-student') // 新生入學異動
        $this->_printReportNewStudent();
        else {
            $this->_redirect('index');
        }
    }

    /**
     *  填入字號
     */
    protected function _assignWord()
    {
        $form = $this->_initForm();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->_getAllParams())) {
                $selSn = $this->_getParam('selSn');
                if (is_array($selSn)) {
                    $tempArr = array();
                    foreach($selSn as $val)
                    $tempArr[] = (int) $val;
                    $q = Doctrine_Query::create()
                    ->update('Student_Model_StudentTransfer')
                    ->set('approve_organ','?', $form->getValue('approve_organ'))
                    ->set('approve_date','?', $form->getValue('approve_date'))
                    ->set('approve_word','?', $form->getValue('approve_word'))
                    ->set('approve_number','?', $form->getValue('approve_number'))
                    ->WhereIn('sn', $tempArr);
                    $q->execute();
                    $this->_helper->json(true);
                }
            }
            else
            $this->_helper->json(array('error'=>$form->getMessages()));

        }
    }

    /**
     * 列印封面
     */
    protected function _printCover()
    {
        if ($this->_getParam('move_kind'))
        $moveKind = $this->_getParam('move_kind');
        else
        $moveKind = 1;

        $ooPath =  dirname(__FILE__) .'/../data/move_cover';
        $ooo = new Sfs_Filesystem_Ooo($ooPath);
        $content = $ooo->getContent('content.xml');
        $arr =array();
        $semester = new Semester_Model_SemesterDuration();
        $semesterArr = $semester->getAllYearSemester();
        $arr['school_long_name']  = $this->view->School['name'];
        if ($this->_getParam('current_semester'))
        $arr['curr_semester']  = $semesterArr[$this->_getParam('current_semester')];
        $arr['sign_date'] = $this->view->TaiwanDate(date("Y-m-d"), Sfs_View_Helper_TaiwanDate::COUNTRY_LONG_NAME);

        if ($moveKind == 1 )
        $arr['move_title'] = '學生異動情形';
        elseif ($moveKind== 2)
        $arr['move_title'] = '新生入學';

        $data = $ooo->change_temp($arr,$content);
        $ooo->add_file($data,'content.xml');
        $ooo->send_odt('cover_paper.odt');
    }

    // 列印新生異動報表
    protected function _printReportNewStudent()
    {
        $year = (int) $this->_getParam('selYear');
        $q = Doctrine_Query::create()
        ->select('a.sn, a.year,a.semester, b.name AS name, b.identification_number AS identification_number ,
          b.sex AS sex ,b.birthday AS birthday, b.address AS address, c.student_id AS student_id')
        ->from('Student_Model_StudentTransfer a')
        ->leftJoin('a.Student_Model_Student b')
        ->leftJoin('b.Student_Model_StudentSemester c')
        ->where('a.year=?', $year)
        ->andWHere('a.year=c.year')
        ->andWHere('a.semester=c.semester')
        ->andWHere('a.causation_kind=?', Student_Model_StudentTransfer::NEW_STUDENT)
        ->orderby('c.student_id');

        $res = $q->fetchArray();
        $this->view->data = $res;
        $ooPath =  dirname(__FILE__) .'/../data/movein';
        $ooo = new Sfs_Filesystem_Ooo($ooPath);
        $str = $this->view->render('report/moveIn/content.phtml');
        $this->view->content= str_replace("\n",'',$str);
        $str =  str_replace("\n",'',$str);

        $ooo->add_file($str,'content.xml');

        $styles = $ooo->getContent('styles.xml');
        $semester = new Semester_Model_SemesterDuration();
        $semesterArr = $semester->getAllYearSemester();
        $arr = array();
        $arr['school_long_name']  = $this->view->School['name'];
        $arr['current_semester']  = $semesterArr[$res[0]['year'].'-'.$res[0]['semester']];
        $arr['report_month'] = $this->view->TaiwanDate(date('Y-m-d'),Sfs_View_Helper_TaiwanDate::YEAR_MONTH);
        $replaceData  = $ooo->change_temp($arr, $styles);
        $ooo->setSkipFile('styles.xml');
        $ooo->add_file($replaceData,'styles.xml');
        $ooo->send_odt($arr['report_month'].'.odt');
    }

    /**
     *  列印異動報表
     */
    protected function _printReport()
    {
        $selSn = $this->_getParam('selSn');
        if (is_array($selSn)) {
            $tempArr = array();
            foreach($selSn as $val)
            $tempArr[] = (int) $val;
            $res = Doctrine_Query::create()
            ->select('a.*, b.name AS name, c.grade AS grade, c.student_id AS student_id')
            ->from('Student_Model_StudentTransfer a')
            ->leftJoin('a.Student_Model_Student b')
            ->leftJoin('b.Student_Model_StudentSemester c')
            ->whereIN('a.sn',$tempArr)
            ->andWHere('a.year=c.year')
            ->andWHere('a.semester=c.semester')
            ->orderBy('a.date')
            ->fetchArray() ;
            $this->view->data = $res;
            $ooPath =  dirname(__FILE__) .'/../data/moveout';
            $ooo = new Sfs_Filesystem_Ooo($ooPath);
            $str = $this->view->render('report/moveOut/content.phtml');
            $this->view->content= str_replace("\n",'',$str);
            $str =  str_replace("\n",'',$str);

            $ooo->add_file($str,'content.xml');

            $styles = $ooo->getContent('styles.xml');
            $semester = new Semester_Model_SemesterDuration();
            $semesterArr = $semester->getAllYearSemester();
            $arr = array();
            $arr['school_long_name']  = $this->view->School['name'];
            $arr['current_semester']  = $semesterArr[$res[0]['year'].'-'.$res[0]['semester']];
            $arr['report_month'] = $this->view->TaiwanDate(date('Y-m-d'),Sfs_View_Helper_TaiwanDate::YEAR_MONTH);
            $arr['move_kind'] =  $this->view->arrayData['study_cond'][$res[0]['causation_kind']];
            $replaceData  = $ooo->change_temp($arr, $styles);
            $ooo->setSkipFile('styles.xml');
            $ooo->add_file($replaceData,'styles.xml');
            $ooo->send_odt($arr['report_month'].'.odt');
        }

    }

    public function getReportAction()
    {
        $this->getHelper('layout')->disableLayout();
        $temp = explode("-", $this->_getParam('yearSemester'));
        $year = (int) $temp[0];
        $semester = (int) $temp[1];
        $moveKind = (int) $this->_getParam('move_kind');
        $this->view->moveKind = $moveKind;
        $form = $this->_initForm();
        $form->setDefault('approve_organ', $this->_studentParamArr['default_approve_organ']);
        $form->setDefault('approve_word', $this->_studentParamArr['default_approve_word']);
        $form->setDefault('approve_date', date('Y-m-d'));
        $this->view->form = $form;
        // TODO 新生入學
        if ($moveKind == Student_Model_StudentTransfer::NEW_STUDENT) {
            $q = Doctrine_Query::create()
            ->select('CONCAT(approve_organ, approve_word,approve_number) AS dif,
                count(*) AS countNumber,
                year,date, approve_organ,approve_word, approve_date,approve_number')
            ->from('Student_Model_StudentTransfer a')
            ->where('causation_kind=?', Student_Model_StudentTransfer::NEW_STUDENT)
            ->orderBy('year DESC')
            ->groupBy('dif');
            $res = $q->fetchArray();
            $this->view->data = $res;
            echo $this->view->render('report/get-report-new-student.phtml');
            exit;
        }
        else {
            $q = Doctrine_Query::create()
            ->select('a.*, b.name AS name, c.student_id AS student_id')
            ->from('Student_Model_StudentTransfer a')
            ->leftJoin('a.Student_Model_Student b')
            ->leftJoin('b.Student_Model_StudentSemester c')
            ->where('a.year=?', $year)
            ->andWhere('a.semester=?', $semester)
            ->andWhere('causation_kind=?', $moveKind)
            ->andWhere('a.year=c.year')
            ->andWHere('a.semester=c.semester')
            ->orderby('a.date DESC');
            $res = $q->fetchArray();
            $this->view->data = $res;
        }
    }

    protected function _initForm()
    {
        $form = new Zend_Form();
        $form->addElement('text','approve_organ',array(
            'label' => 'approve organ',
            'size' => 20,
            'required' => true,
            'filters' => array('stripTags','stringTrim')
        ));

        $form->addElement('text','approve_date',array(
            'label' => 'approve date',
            'size' => 20,
            'required' => true,
            'validates' => array('date')
        ));

        $form->addElement('text','approve_word',array(
            'label' => 'approve word',
            'size' => 20,
            'required' => true,
            'filters' => array('stripTags','stringTrim')
        ));

        $form->addElement('text','approve_number',array(
            'label' => 'approve number',
            'size' => 20,
            'required' => true,
            'filters' => array('stripTags','stringTrim')
        ));

        return $form;
    }

}

